package com.ntv.presentation.spring.web.user;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.ntv.domain.User;

public class UserValidator implements Validator {

	private final Validator userValidator;

	public UserValidator(Validator userValidator) {
		if (userValidator == null) {
			throw new IllegalArgumentException(
					"The supplied [Validator] is required and must not be null.");
		}
		if (!userValidator.supports(User.class)) {
			throw new IllegalArgumentException(
					"The supplied [Validator] must support the validation of [User] instances.");
		}
		this.userValidator = userValidator;
	}

	/**
	 * This Validator validates Customer instances, and any subclasses of
	 * Customer too
	 */
	public boolean supports(Class clazz) {
		return User.class.isAssignableFrom(clazz);
	}

	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "field.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "surname", "field.required");
		User user = (User) target;
		try {
			errors.pushNestedPath("user");
			ValidationUtils.invokeValidator(this.userValidator, user, errors);
		} finally {
			errors.popNestedPath();
		}
	}

}
